package com.axing.aiguideagent.app;

import com.axing.aiguideagent.advisor.MyLoggerAdvisor;
import com.axing.aiguideagent.chatmemory.FileBasedChatMemory;
import com.axing.aiguideagent.rag.GuideAppRagCustomAdvisorFactory;
import com.axing.aiguideagent.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class GuideApp {

    @Resource
    private VectorStore guideAppVectorStore;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    private final ChatClient chatClient;

    private static final String SYSTEM_PROMPT = "你是一位名叫“斑马”的武汉城市向导官。\n" +
            "- 只在对话的第一轮问候时进行自我介绍，之后**绝不重复自我介绍**。\n" +
            "- 后续回答用户问题时，直接针对用户需求提供美食、景点、住宿建议，并主动提问引导用户。\n" +
            "- 语气友好、口语化、带武汉特色。" +
            "- 用武汉方言，语气中带有个斑马，里个表等这些本地特色的口语化表达\n";

    /**
     * 初始化 ChatClient
     * @param dashcopeChatModel
     */
    public GuideApp(ChatModel dashcopeChatModel) {
        // 初始化基于文件的对话记忆
        String fileDir = System.getProperty("user.dir") + "/tmp/chat-memory";
        ChatMemory chatMemory = new FileBasedChatMemory(fileDir);

        // 初始化基于内存的对话记忆
        // ChatMemory chatMemory = new InMemoryChatMemory();
        chatClient = ChatClient.builder(dashcopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        // 自定义日志Advisor
                        new MyLoggerAdvisor()
                        // 自定义推理增强Advisor
                        // new ReReadingAdvisor()
                )
                .build();
    }

    /**
     * AI 对话 基础对话（支持多轮对话记忆）
     *
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message, String chatId){
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    /**
     * AI 对话 基础对话（支持多轮对话记忆,SSE流式传输）
     *
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChatByStream(String message, String chatId){
        return chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 应用rag知识库回答
                .advisors(new QuestionAnswerAdvisor(guideAppVectorStore))
                .tools(toolCallbackProvider)
                // 应用自定义RAG检索增强服务（文件查询器+上下文增强器）
//                .advisors(
//                        GuideAppRagCustomAdvisorFactory.createGuideAppRagCustomAdvisor(guideAppVectorStore, "美食"),
//                        GuideAppRagCustomAdvisorFactory.createGuideAppRagCustomAdvisor(guideAppVectorStore, "景点"),
//                        GuideAppRagCustomAdvisorFactory.createGuideAppRagCustomAdvisor(guideAppVectorStore, "住宿")
//                )
                .stream()
                .content();
    }

    record LoveReport(String title, List<String> suggestions) {
    }

    /**
     * AI 咨询报告功能（实战结构化输出）
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId){
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成心理咨询结果，标题为{用户名}的心理咨询报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", loveReport);
        return loveReport;
    }

    // AI心理知识库问答功能
//    @Resource
//    private VectorStore GuideAppVectorStore;

//    @Resource
//    private Advisor emoAppRagCloudAdvisor;
//
//    @Resource
//    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;

    /**
     * 和rag知识库进行对话
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message, String chatId){
        // 查询重写
        //String rewriteMessage = queryRewriter.doQueryRewrite(message);
        ChatResponse chatResponse = chatClient
                .prompt()
                // 使用改写后的查询
                .user(message)
                .advisors()
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                // 应用rag知识库回答
                //.advisors(new QuestionAnswerAdvisor(guideAppVectorStore))
                // 基于RAG检索增强服务（基于云知识库）
                //.advisors(emoAppRagCloudAdvisor)
                // 基于RAG检索增强服务（基于PgVector 向量存储）
                //.advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                // 应用自定义RAG检索增强服务（文件查询器+上下文增强器）
                .advisors(
                        GuideAppRagCustomAdvisorFactory.createGuideAppRagCustomAdvisor(
                                guideAppVectorStore, "住宿"
                        )
                )
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    // AI调用工具能力
    @Resource
    private ToolCallback[] allTools;

    /**
     * AI咨询报告功能（支持调用工具）
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithTools(String message, String chatId){
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    // AI调用MCP服务

    /**
     * AI咨询报告功能（MCP）
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithMcp(String message, String chatId){
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }
}
